import React, {Component} from 'react'
import {Button, Card, Form, Image, Input, message, Modal, Popconfirm, Space, Spin} from 'antd';
import SlidePicture from '../../../../types/indexPage';
import {addSlidesPicture, deleteSlidePicture, slideReq} from '../../../../requests/indexPage';
import {getRes} from '../../../../configFile';
import {Store, ValidateErrorEntity} from 'rc-field-form/lib/interface'
import {FormInstance} from 'antd/lib/form';


interface IProps { }
interface IState {
	originCaro: Array<SlidePicture>
	newCaro: File | undefined
	isLoading: boolean
	addCaroModalVisible: boolean
}
export default class ModifyCarousel extends Component<IProps, IState> {
	//使用ref获取数据域
	formRef = React.createRef<FormInstance>()
	constructor(props: IProps) {
		super(props)
		this.state = {
			addCaroModalVisible: false,
			isLoading: true,
			newCaro: undefined,
			originCaro: []
		}
	}
	//获取轮播图
	getCaro = async () => {
		try {
			const res = getRes(await slideReq())
			this.setState({
				...this.state,
				originCaro: res.data
			})
		} catch (err) {
			message.error(err.toString())
		} finally {
			this.setState({
				...this.state,
				isLoading: false
			})
		}
	}
	async componentDidMount() {
		this.getCaro()
	}

	onAddChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		const { files } = e.target;
		if (files) {
			this.setState({
				newCaro: files[0]
			})
		}
	}
	//删除对应轮播图
	onDeleteCaro = async (caroID: number) => {
		try {
			this.setState({
				...this.state,
				isLoading: true
			})
			const res = getRes(await deleteSlidePicture(caroID))
			console.log(res);

			if (res.isSuccessful === true) {
				message.success('删除成功')
				this.getCaro()
			} else {
				message.error(res.message)
			}
		} catch (err) {
			message.error(err.toString())
		} finally {
			this.setState({
				...this.state,
				isLoading: false
			})
		}
	}


	//模态框操作
	/*模态框表单样式*/
	modalLayout = {
		labelCol: { span: 8 },
		wrapperCol: { span: 14 },
	};
	modalTailLayout = {
		wrapperCol: { offset: 8 },
	};
	//显示模态框
	showModal = () => {
		this.setState({
			...this.state,
			addCaroModalVisible: true,
		});
	};
	//关闭模态框
	addCaroHandleCancel = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
		this.setState({
			...this.state,
			addCaroModalVisible: false,
		});
	};
	//模态框提交成功
	onModalFinish: (values: Store) => void = async values => {
		try {
			this.setState({ isLoading: true })
			if (!!this.state.newCaro) {
				const res = getRes(await addSlidesPicture(this.state.newCaro, values.description))
				if (res.isSuccessful === true) {
					message.success("增加成功")
				} else {
					message.error("增加失败"+res.message)
				}
			}
		} catch (err) {
			message.error(err.toString())
		} finally {
			await this.getCaro();
			this.setState({
				...this.state,
				isLoading: false
			})
			//关闭模态框
			this.setState({
				addCaroModalVisible: false,
			});
		}
	}
	//模态框提交失败
	onModalFinishFailed = (errorInfo: ValidateErrorEntity) => {
		message.error(errorInfo.errorFields[0].errors[0]);
	};


	render() {
		return (
			<div>
				<Card
					title="轮播图设置"
					extra={
						<Button type="primary" onClick={this.showModal}>新增</Button>
					}
				>
					<Spin spinning={this.state.isLoading}>
						{this.state.originCaro.map(item =>
							<Space>
								<Image src={item.slidePath} placeholder={`轮播图 ${item.slidePictureID} ${item.slideDescription}`} style={{ marginTop: '10px', minHeight: '288px', minWidth: '900px' }} />
								<Popconfirm
									title="确认删除吗？"
									okText="确认"
									cancelText="取消"
									onConfirm={this.onDeleteCaro.bind(this, item.slidePictureID)}
								>
									<Button danger size="large">删除</Button>
								</Popconfirm>
							</Space>
						)}

						{/* 新增图片模态框 */}
						<Modal
							title="新增首页轮播图"
							visible={this.state.addCaroModalVisible}
							onCancel={this.addCaroHandleCancel}
							footer={null}
						>
							<Spin spinning={this.state.isLoading}>
								<Form
									onFinishFailed={this.onModalFinishFailed}
									onFinish={this.onModalFinish}
									ref={this.formRef}
									{...this.modalLayout}
									name="addCaro"
									hideRequiredMark
								>

									<Form.Item
										name="description"
										label="轮播图简介"
										rules={[
											{
												required: true,
											}
										]}
										hasFeedback
									>
										<Input type="text" />
									</Form.Item>

									<Form.Item
										name="caroFile"
										label="图片（1280*410）"
										hasFeedback={true}
										rules={[
											{
												required: true,
												message: '请上传文件',
											}
										]}
									>
										<Input
											type="file"
											onChange={this.onAddChange}
											accept={"image/*"}
										>
										</Input>
									</Form.Item>
									<Form.Item {...this.modalTailLayout}>
										<Button type="primary" htmlType="submit">
											确认修改
                             			</Button>
									</Form.Item>
								</Form>
							</Spin>
						</Modal>
					</Spin>
				</Card >

			</div >
		)
	}
}
